<template>
    <div class="panel device-data-charts">
      <h2 class="panel-title">设备监控数据</h2>
      <div class="chart-controls">
        <div class="time-range">
          <span 
            v-for="range in timeRanges" 
            :key="range"
            :class="['range-item', { active: currentRange === range }]"
            @click="changeTimeRange(range)"
          >
            {{ range }}
          </span>
        </div>
      </div>
      <div class="charts-container">
        <div class="chart-row">
          <div class="chart-item">
            <div ref="soilMoistureChart" class="chart"></div>
          </div>
          <div class="chart-item">
            <div ref="soilTempChart" class="chart"></div>
          </div>
        </div>
        <div class="chart-row">
          <div class="chart-item">
            <div ref="soilNitrogenChart" class="chart"></div>
          </div>
          <div class="chart-item">
            <div ref="airTempChart" class="chart"></div>
          </div>
        </div>
        <div class="chart-row">
          <div class="chart-item center">
            <div ref="co2Chart" class="chart"></div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue'
  import * as echarts from 'echarts'
  import { sensorApi } from '@/api'
  
  const timeRanges = ['24小时', '7天', '30天']
  const currentRange = ref('24小时')
  
  // 图表引用
  const soilMoistureChart = ref(null)
  const soilTempChart = ref(null)
  const soilNitrogenChart = ref(null)
  const airTempChart = ref(null)
  const co2Chart = ref(null)
  
  // 图表实例
  let charts = {
    soilMoisture: null,
    soilTemp: null,
    soilNitrogen: null,
    airTemp: null,
    co2: null
  }
  
  // 初始化图表
  const initChart = (ref, title, unit) => {
    const chart = echarts.init(ref)
    chart.setOption({
      title: { 
        text: title,
        textStyle: { color: '#fff', fontSize: 14 }
      },
      tooltip: { 
        trigger: 'axis',
        formatter: `{b}<br/>{a}: {c}${unit}`
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        axisLabel: { color: '#fff' },
        data: []
      },
      yAxis: {
        type: 'value',
        axisLabel: { color: '#fff' }
      },
      series: [{
        name: title,
        type: 'line',
        smooth: true,
        data: [],
        areaStyle: {
          opacity: 0.1
        },
        itemStyle: {
          color: '#42b983'
        }
      }]
    })
    return chart
  }
  
  // 更新图表数据
  const updateCharts = async () => {
    try {
      // 获取最新数据
      const latestData = await sensorApi.getLatestData()
      
      // 获取历史数据
      const page = 0
      const size = currentRange.value === '24小时' ? 24 : 
                   currentRange.value === '7天' ? 7 : 30
  
      const types = ['soilmoisture', 'soiltemperature', 'soilnitrogen', 'airtemperature', 'carbondioxide']
      const historicalData = await Promise.all(
        types.map(type => sensorApi.getHistoricalData(type, page, size))
      )
  
      // 更新各个图表
      updateSingleChart(charts.soilMoisture, historicalData[0], '土壤湿度', '%')
      updateSingleChart(charts.soilTemp, historicalData[1], '土壤温度', '℃')
      updateSingleChart(charts.soilNitrogen, historicalData[2], '土壤氮含量', 'mg/kg')
      updateSingleChart(charts.airTemp, historicalData[3], '空气温度', '℃')
      updateSingleChart(charts.co2, historicalData[4], '二氧化碳浓度', 'ppm')
    } catch (error) {
      console.error('Failed to update charts:', error)
    }
  }
  
  const updateSingleChart = (chart, data, name, unit) => {
    const times = data.content.map(item => 
      new Date(item.createTime).toLocaleTimeString('zh', {
        hour: '2-digit',
        minute: '2-digit'
      })
    )
    const values = data.content.map(item => item.value)
  
    chart.setOption({
      xAxis: { data: times },
      series: [{
        name,
        data: values
      }]
    })
  }
  
  // 切换时间范围
  const changeTimeRange = (range) => {
    currentRange.value = range
    updateCharts()
  }
  
  // 初始化所有图表
  onMounted(() => {
    charts.soilMoisture = initChart(soilMoistureChart.value, '土壤湿度', '%')
    charts.soilTemp = initChart(soilTempChart.value, '土壤温度', '℃')
    charts.soilNitrogen = initChart(soilNitrogenChart.value, '土壤氮含量', 'mg/kg')
    charts.airTemp = initChart(airTempChart.value, '空气温度', '℃')
    charts.co2 = initChart(co2Chart.value, '二氧化碳浓度', 'ppm')
  
    updateCharts()
  
    // 自动更新
    const timer = setInterval(updateCharts, 60000) // 每分钟更新一次
  
    // 窗口大小改变时重绘图表
    window.addEventListener('resize', () => {
      Object.values(charts).forEach(chart => chart?.resize())
    })
  
    onUnmounted(() => {
      clearInterval(timer)
      Object.values(charts).forEach(chart => chart?.dispose())
    })
  })
  </script>
  
  <style scoped>
  .device-data-charts {
    height: 100%;
    padding: 15px;
  }
  
  .chart-controls {
    margin-bottom: 15px;
  }
  
  .time-range {
    display: flex;
    gap: 15px;
  }
  
  .range-item {
    color: #888;
    cursor: pointer;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 14px;
  }
  
  .range-item:hover {
    color: #42b983;
  }
  
  .range-item.active {
    background: #42b983;
    color: #fff;
  }
  
  .charts-container {
    height: calc(100% - 60px);
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .chart-row {
    flex: 1;
    display: flex;
    gap: 15px;
  }
  
  .chart-item {
    flex: 1;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    padding: 10px;
  }
  
  .chart-item.center {
    margin: 0 auto;
    width: 50%;
  }
  
  .chart {
    width: 100%;
    height: 100%;
  }
  </style>